package lambdasinaction.chap5;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by zhuyisheng
 * Date: 2018/5/29 0029 上午 10:04
 */
public class flatMapTest {

    /**
     * 去除重复单词
     *
     * @param args
     */
    public static void main(String[] args) {
        List<String> list = Arrays.asList("hello welcome", "world hello", "hello world", "hello world welcome");

        //A:
        System.out.println("A:  Stream -> map  输出结果：");
        /**
         * java.util.stream.ReferencePipeline$Head@6acbcfc0
         * java.util.stream.ReferencePipeline$Head@5f184fc6
         * java.util.stream.ReferencePipeline$Head@3feba861
         * java.util.stream.ReferencePipeline$Head@5b480cf9
         */
        list.stream().map(str -> Arrays.stream(str.split(" "))).distinct().collect(Collectors.toList()).forEach(System.out::println);

        System.out.println();

        //B:
        System.out.println("B:  Stream -> map  返回类型：List<Stream<String>>");
        List<Stream<String>> listStream = list.stream().map(str -> Arrays.stream(str.split(" "))).distinct().collect(Collectors.toList());

        System.out.println();


        //TODO 等同于(分部写)
        System.out.println("测试  Stream -> map (分部写) 输出结果：");
        Stream<String[]> stream = list.stream().map(str -> str.split(" "));
        Stream<Stream<String>> streamStream = stream.map(strings1 -> Arrays.stream(strings1));
        List<Stream<String>> listStream1 = streamStream.collect(Collectors.toList());
        for (Stream<String> s: listStream1) {
            List<String> listString = s.distinct().collect(Collectors.toList());
            for(String str: listString) {
                System.out.println(str);
            }
            System.out.println();
        }

        System.out.println("----------------------------------------");


        //C:
        System.out.println("C:  Stream -> flatMap  输出结果：");
        /**
         * hello
         * welcome
         * world
         */
        list.stream().flatMap(str -> Arrays.stream(str.split(" "))).distinct().collect(Collectors.toList()).forEach(System.out::println);

        System.out.println();

        //D:
        System.out.println("D:  Stream -> flatMap  返回类型：List<String>");
        List<String> listResult2 = list.stream().flatMap(str -> Arrays.stream(str.split(" "))).distinct().collect(Collectors.toList());
    }
}
